package com.dd.machine.base.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public class CommomUtils {
	private final static double PI = 3.14159265358979323; // 圆周率
	private final static double R = 6371229; // 地球的半径
	private static int commomId = 1;

	// 颜色值转换
	public static int colorBurn(int RGBValues) {
		int alpha = 160;
		int red = RGBValues >> 16 & 0xFF;
		int green = RGBValues >> 8 & 0xFF;
		int blue = RGBValues & 0xFF;
		red = (int) Math.floor(red * (1 - 0.1));
		green = (int) Math.floor(green * (1 - 0.1));
		blue = (int) Math.floor(blue * (1 - 0.1));
		return Color.argb(alpha, red, green, blue);
	}
	/**
	 * 单位： 米
	 * 
	 * @param longt1
	 * @param lat1
	 * @param longt2
	 * @param lat2
	 * @return
	 */
	public static double getDistance(double longt1, double lat1, double longt2,
			double lat2) {
		double x, y, distance;
		x = (longt2 - longt1) * PI * R
				* Math.cos(((lat1 + lat2) / 2) * PI / 180) / 180;
		y = (lat2 - lat1) * PI * R / 180;
		distance = Math.hypot(x, y);
		return distance;
	}
	/**
	 * 单位：千 米
	 * 
	 * @param longt1
	 * @param lat1
	 * @param longt2
	 * @param lat2
	 * @return
	 */
	public static String getDistanceKM(double longt1, double lat1, double longt2,
									   double lat2) {
		double x, y, distance;
		x = (longt2 - longt1) * PI * R
				* Math.cos(((lat1 + lat2) / 2) * PI / 180) / 180;
		y = (lat2 - lat1) * PI * R / 180;
		distance = Math.hypot(x, y);
		double dis = 0;
		dis = Math.round(distance / 100d)/10d;
		return dis+"Km ";
//		if(distance>1000){
//			return (int) (distance/1000)+"  km";
//		}else{
//			return (int) distance+"   m";
//		}
	}
	public static String getCurrentTime(String format) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
		String currentTime = sdf.format(date);
		return currentTime;
	}

	public static String getCurrentTime() {
		return getCurrentTime("yyyy-MM-dd  HH:mm:ss");
	}
	public static Double roundDouble(double val, int precision) {
		Double ret = null;
		try {
			double factor = Math.pow(10, precision);
			ret = Math.floor(val * factor + 0.5) / factor;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ret;
	}

	public static String roundDouble(double val) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("#.000");
		return df.format(val);
	}
	public static String DoubleToString(double d){
		String str=d+"";
		str=str.substring(0,str.lastIndexOf("."));
		return str;
	}
	public static String DoubleToString(Object cache){
		double d=(Double)cache;
		String str=d+"";
		str=str.substring(0,str.lastIndexOf("."));
		return str;
	}
	/**
	 * 手机端时间的显示问题（包括路况与截图），需要和手机的时间进行匹配，
	 * 分为：刚刚，1分钟前，5分钟前，15分钟前，30分钟前，1小时前，x小时前（一天内）
	 * ，昨天 xx:xx，前天 xx:xx，xx月xx日 xx:xx，要求超过时间区域可以自动刷新。
	 * @param d
	 * @return
	 */
	public static String DoubleToDate(double d){
		Date dd=new Date();
		long curTime=dd.getTime();
		long t=(long)(d);
		long period=curTime-t;
		
		Calendar calendar= Calendar.getInstance();
		int curH=calendar.get(Calendar.HOUR_OF_DAY);
		int curS=calendar.get(Calendar.SECOND);
		int curM=calendar.get(Calendar.MINUTE);
		int curPeriod=curH*60*60*1000+curM*60*1000+curS*1000;
		if(period<1000*60){
			return "刚刚";
		}else if(period>=1000*60&&period<1000*60*5){
			return "1分钟前";
		}else if(period>=1000*60*5&&period<1000*60*15){
			return "5分钟前";
		}else if(period>=1000*60*15&&period<1000*60*30){
			return "15分钟前";
		}else if(period>=1000*60*30&&period<1000*60*60){
			return "30分钟前";
		}else if(period>1000*60*60&&period<=curPeriod){
			int h=(int)period/(1000*60*60);
			return h+"小时前";
			
		}else if(period>curPeriod&&period<=(1000*60*60*24+curPeriod)){
			Date date=new Date(t);
			SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getInstance();
			sdf.applyPattern("HH:mm");
			String dateStr=sdf.format(date);
			return "昨天"+dateStr;
		}else if(period>(1000*60*60*24+curPeriod)&&period<=(1000*60*60*48+curPeriod)){
			Date date=new Date(t);
			SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getInstance();
			sdf.applyPattern("HH:mm");
			String dateStr=sdf.format(date);
			return "前天"+dateStr;
		}else{
			Date date=new Date(t);
			SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getInstance();
			sdf.applyPattern("MM月dd日 HH:mm");
			String dateStr=sdf.format(date);
			return dateStr;
		}
		
		
	}
	public static String DoubleToDateNomarl(double d){
			long t=(long)(d);
			Date date=new Date(t);
			SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getInstance();
			sdf.applyPattern("yyyy年MM月dd日 HH:mm");
			String dateStr=sdf.format(date);
			return dateStr;
		
		
	}
	/**
	 * 获取版本号
	 * @return 当前应用的版本号
	 */
	public static String getVersion(Context ctx) {
	    try {
	        PackageManager manager = ctx.getPackageManager();
	        PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
	        String version = info.versionName;
	        return  version;
	    } catch (Exception e) {
	        e.printStackTrace();
	        return null;
	    }
	}
	/**
	 * 将时间秒转化为表义格式
	 * @param seconds
	 * @return
	 */
	public static String doubleToTime(long seconds){
		if(seconds<60){
			return seconds+"秒";
		}
		long minutes=seconds/60;
		if(minutes<60){
			return minutes+"分钟";
		}else{
			long hour=minutes/60;//小时
			long min=minutes-hour*60;//分钟
			if(hour<24){
				if(min!=0){
					return hour+"小时"+min+"分钟";
				}else{
					return hour+"小时";
				}
			}else{
				long day=hour/24;
				long h=hour-day*24;
				if(h!=0){
					long m=min-day*24*60-h*60;
					if(m!=0){
						return day+"天"+h+"小时"+m+"分钟";
					}else{
						return day+"天"+h+"小时";
					}
				}else{
					long m=min-day*24*60-h*60;
					if(m!=0){
						return day+"天"+m+"分钟";
					}else{
						return day+"天";
					}
				}
			}
		}
	}
	
	/**
	 * 将时间秒转化为表义格式（带空格）
	 * @param seconds
	 * @return
	 */
	public static String doubleToTimeWithSpace(long seconds){
		if(seconds<60){
			return seconds+" 秒";
		}
		long minutes=seconds/60;
		if(minutes<60){
			return minutes+" 分钟";
		}else{
			long hour=minutes/60;//小时
			long min=minutes-hour*60;//分钟
			if(hour<24){
				if(min!=0){
					return hour+" 小时"+min+" 分钟";
				}else{
					return hour+" 小时";
				}
			}else{
				long day=hour/24;
				long h=hour-day*24;
				if(h!=0){
					long m=min-day*24*60-h*60;
					if(m!=0){
						return day+" 天"+h+" 小时"+m+" 分钟";
					}else{
						return day+" 天"+h+" 小时";
					}
				}else{
					long m=min-day*24*60-h*60;
					if(m!=0){
						return day+" 天"+m+" 分钟";
					}else{
						return day+" 天";
					}
				}
			}
		}
	}
	
	/**
	 * 生成0-9的随机数
	 * @return
	 */
	public static int getRandom(){
		int number = new Random().nextInt(10) + 1;
		return number;
	}
	private static long lastClickTime;
	/**
	 * 防止重复判断
	 * @return  true/false
	 */
	public static boolean isFastDoubleClick(int id) {
		if(commomId==id){
			long time = System.currentTimeMillis();
			long timeD = time - lastClickTime;
			if (0 < timeD && timeD < 800) {
				return true;
			}
			lastClickTime = time;
			return false;
		}else{
			commomId=id;
			return false;
		}

	}
	/**
	 * 防止重复判断
	 * @return  true/false
	 */
	private static long showLastTime;
	public static boolean isToastShow() {
		long time = System.currentTimeMillis();
		long timeD = time - showLastTime;
		if (0 < timeD && timeD < 1000) {
			return true;
		}
		showLastTime = time;
		return false;
	}
	public static int getScreenW(Context ctx){
		WindowManager manager = (WindowManager)ctx.getSystemService(Context.WINDOW_SERVICE);
	    Display display = manager.getDefaultDisplay();
		return display.getWidth(); // 屏幕宽（像素，如：480px）  
	}
	public static int getScreenH(Context ctx){
		WindowManager manager = (WindowManager)ctx.getSystemService(Context.WINDOW_SERVICE);
	    Display display = manager.getDefaultDisplay();
		return display.getHeight(); // 屏幕宽（像素，如：480px）  
	}
	
	/**
	 * 获取手机像素密度
	 * @return
	 */
	public static int getDPI(Activity activity){
		DisplayMetrics metric = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metric);

		int width = metric.widthPixels; // 宽度（PX）
		int height = metric.heightPixels; // 高度（PX）

		float density = metric.density; // 密度（0.75 / 1.0 / 1.5）
		int densityDpi = metric.densityDpi; // 密度DPI（120 / 160 / 240）
		return densityDpi;
	}
	/**
	 * 将服务端返回的桩号显示成K34+500的格式
	 * @param pileNo
	 * @return
	 */
	public static String getPileNo(String pileNo){
		String hint = null;
		if("".equals(pileNo)||pileNo==null){
			hint = "K0";
		}else{
			int index = pileNo.indexOf(".");
			if(index>0){
				String k = pileNo.substring(0, index);
				String e = pileNo.substring(index+1, pileNo.length());
				if("0".equals(e)||"".equals(e)){
					hint = "K"+k+"+000";
				}else{
					if(e.length()==1){
						hint = "K"+k+"+"+e+"00";
					}else if(e.length()==2){
						hint = "K"+k+"+"+e+"0";
					}else if(e.length()==3){
						hint = "K"+k+"+"+e;
					}else{
						hint = "K"+k+"+"+e.substring(0, 3);
					}
				}
			}else{
				hint = "K"+pileNo.trim();
			}
		}
		return hint;
	}
}
